//
//  PersonalViewController.m
//  LiveEducation
//
//  Created by Liu,Qingcan on 2017/4/11.
//  Copyright © 2017年 Baidu. All rights reserved.
//

#import "PersonalViewController.h"
#import "StatusTableViewCell.h"
#import "SettingsTableViewCell.h"
#import "StatusButton.h"
#import "UIView+LEBezierPath.h"
#import "UIView+WLExtension.h"
#import "StatusViewController.h"
#import "LoginViewController.h"
#import "UserModel.h"

#import "CacheManangerViewController.h"


#define HEADER_IMAGE_HEIGHT 135
#define NaviBarHeight 64
#define StatusBarHeight 20

@interface PersonalViewController ()<UITableViewDelegate,UITableViewDataSource,StatusCellDelegate>

@property (nonatomic,strong) UITableView *myTableView;
/**顶部头像栏*/
@property (nonatomic,strong) UIImageView *headerImageView;

@property (nonatomic,strong) UIView *backHeaderView;
@property (nonatomic,strong) UIImageView *userHeadImageView;
@property (nonatomic,strong) UIButton *loginButton;
@property (nonatomic,strong) UILabel *usernameLabel;
@property (nonatomic,strong) StatusTableViewCell *statusCell;
@end

@implementation PersonalViewController

#pragma mark lifecircle
//
//- (void)loadView{
//    // 应该是还没有生成view
////    self.view.backgroundColor = [UIColor whiteColor];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupView];

    
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self theLoginBtnWillChanged];
    
    [self.navigationController setNavigationBarHidden:YES];
    self.tabBarController.tabBar.hidden = NO;
//    [self.tabBarController hidesBottomBarWhenPushed];
//    [self.tabBarController setHidesBottomBarWhenPushed:NO];
    
//    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    [self.navigationController setNavigationBarHidden:NO];
   
//    [self.tabBarController setHidesBottomBarWhenPushed:YES];
//    self.navigationController.navigationBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillLayoutSubviews{
//    self.loginButton = nil;
//    self.usernameLabel = nil;
    
    self.backHeaderView.frame = CGRectMake(self.view.bounds.size.width/2.f - 35, -50, 70, 100);
    self.loginButton.frame = CGRectMake(0, 0, 70, 15);
    self.usernameLabel.frame = CGRectMake(0, -20, 70, 15);
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL user_login_status = [defaults boolForKey:@"user_login_status"];
    if (!user_login_status){
        _usernameLabel.hidden = YES;
    }else{

        UserModel *userDao = [[UserModel alloc]init];
        NSArray *arr = [userDao selectNumberOfData:0];
        User *userItem = arr.firstObject;
        _usernameLabel.text = userItem.username;
        _usernameLabel.textColor = [UIColor whiteColor];
        _usernameLabel.font = [UIFont systemFontOfSize:9.8f];
        _usernameLabel.hidden = NO;
    }

    
    
}

#pragma mark delegate
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footer = [[UIView alloc] init];
    if (section == 0) {
//        footer.frame = CGRectMake(0, 0, self.view.bounds.size.width, 30);
        footer.backgroundColor = [UIColor colorWithRed:220.f/255 green:220.f/255 blue:220.f/255 alpha:1.f];
    }
    return footer;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 20;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0 && indexPath.section == 0) {
        return 100;
    }else if(indexPath.section == 0 && indexPath.row != 0){
        return 30;
    }else if (indexPath.section != 0){
        return 50;
    }
    return 44;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        return 4;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"statusCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
   
    if (!cell) {
            if (indexPath.section == 0) {
                cell = [StatusTableViewCell cellWithTableView:tableView];
                
                //            cell = (StatusTableViewCell *)cell;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                self.statusCell   = (StatusTableViewCell *)cell;
                self.statusCell.delegate = self;
                
            }else{
                if (indexPath.row==0) {
                     cell = [SettingsTableViewCell initWithTableView:tableView imageName:@"cache" title:@"缓存管理"];
                }else if (indexPath.row == 1){
                     cell = [SettingsTableViewCell initWithTableView:tableView imageName:@"money" title:@"我的金钱"];
                }else if (indexPath.row == 2){
                     cell = [SettingsTableViewCell initWithTableView:tableView imageName:@"about" title:@"关于我们"];
                }else if (indexPath.row == 3){
                    cell = [SettingsTableViewCell initWithTableView:tableView imageName:@"connect" title:@"联系我们"];
                }
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

//                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            }
    }
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section != 0){
       [tableView deselectRowAtIndexPath:indexPath animated:YES];
        if (indexPath.row == 0) {
            CacheManangerViewController *cacheMngVC = [CacheManangerViewController new];
            [self.navigationController pushViewController:cacheMngVC animated:YES];
        }else if (indexPath.row == 1){
            [self presentAlert];
        }else if (indexPath.row == 2){
            [self presentAboutUsAlert];
        }else if (indexPath.row == 3){
            [self presentConnectUsAlert];
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    CGFloat offsetY = _myTableView.contentOffset.y;
//    NSLog(@"88888 ** %f",offsetY);
//    CGFloat originOffset = - (NaviBarHeight + offsetY);
//    NSLog(@"88eee888 ** %f",offsetY);
//
//    
////    CGFloat scale = originOffset / (_headerImageView.WL_width/4.f +_headerImageView.WL_height);
//    
//    if (offsetY < -NaviBarHeight-HEADER_IMAGE_HEIGHT) {
////        if (offsetY < -kHEIGHT) {
//            CGRect rect = _headerImageView.frame;
//            rect.origin.y = offsetY;
//            rect.size.height = -offsetY;
//            _headerImageView.frame = rect;
////        }
//
//    }
    
    CGPoint point = scrollView.contentOffset; //170
    if (point.y < -(HEADER_IMAGE_HEIGHT)) {
        CGRect rect = _headerImageView.frame;
        rect.origin.y = point.y;
        rect.size.height = -point.y + HEADER_IMAGE_HEIGHT + StatusBarHeight;
        _headerImageView.frame = rect;
    }


    
}

#pragma mark StatusCellDelegate
- (void)didClickedStatusButton:(StatusButton *)button{
    NSLog(@"=== %ld  ",(long)button.tag);
    StatusViewController *statusVC = nil;
    switch (button.tag) {
        case 0://观看记录
            statusVC = [[StatusViewController alloc]initWithUserStatus:LERecordsStatus];
            break;
        case 1://收藏记录
            statusVC = [[StatusViewController alloc]initWithUserStatus:LECollectionStatus];
            break;
        case 2://直播记录
            statusVC = [[StatusViewController alloc]initWithUserStatus:LEMoreStatus];
            break;
        default:
            break;
    }
//    [self.tabBarController.navigationController setNavigationBarHidden:NO];
     self.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:statusVC animated:YES];
}

#pragma mark event response

- (void)presentAlert{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"金钱" message:@"您暂时还没有相关金钱" preferredStyle:UIAlertControllerStyleAlert];
    
//    __weak typeof(self) wself = self;
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //                        [wself popoverPresentationController];
        //        [wself.navigationController popViewControllerAnimated:YES];
    }];
    [alertVC addAction:okAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}


- (void)presentAboutUsAlert{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"关于作品" message:@"在线教育直播类app \n author:chge" preferredStyle:UIAlertControllerStyleAlert];
    
    //    __weak typeof(self) wself = self;
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //                        [wself popoverPresentationController];
        //        [wself.navigationController popViewControllerAnimated:YES];
    }];
    [alertVC addAction:okAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}


- (void)presentConnectUsAlert{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"联系方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    //    __weak typeof(self) wself = self;
    UIAlertAction *phoneAction = [UIAlertAction actionWithTitle:@"电话: 13398390411" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        //                        [wself popoverPresentationController];
        //        [wself.navigationController popViewControllerAnimated:YES];
    }];
    UIAlertAction *emailAction = [UIAlertAction actionWithTitle:@"email: lqc_loadingu@163.com" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        //                        [wself popoverPresentationController];
        //        [wself.navigationController popViewControllerAnimated:YES];
    }];
    
    
    [alertVC addAction:phoneAction];
    [alertVC addAction:emailAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}




- (void)didClickedUserHeaderImageView:(UITapGestureRecognizer *)sender{
    NSLog(@"clicked userImage");
     if ([ self.loginButton.currentTitle isEqualToString:@"注销"]) {
         
     }else{
         LoginViewController *loginVC = [[LoginViewController alloc]init];
         
         self.tabBarController.tabBar.hidden = YES;
         [self.navigationController pushViewController:loginVC animated:YES];
     }
    
}

- (void)didClickedLoginButton:(UIButton *)sender{
    NSLog(@"clicked loginButton");
    
    if ([sender.currentTitle isEqualToString:@"注销"]) {
        //本地数据库删除用户数据
        UserModel *userDao = [[UserModel alloc]init];
        [userDao deleteAllUser];

        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setBool:NO forKey:@"user_login_status"];

        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"注意！" message:@"你已经注销了！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES
                         completion:nil];
        
        
        [self theLoginBtnWillChanged];
//        [self viewWillLayoutSubviews]; 也是可以的
    
        
//        self.view.bounds = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height + 1);
        
//        self.loginButton.userInteractionEnabled = NO;
       
//        [self.view bringSubviewToFront:self.loginButton];
//        [self.view setNeedsDisplay];
//        [self.view layoutIfNeeded];
    }
    
    
}




#pragma mark private
- (void)setupView{
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.myTableView];
    
    [self.myTableView addSubview:self.headerImageView];
//    self.myTableView.tableHeaderView = self.headerImageView;
    [self.myTableView addSubview:self.backHeaderView];
    
    [self.backHeaderView addSubview:self.userHeadImageView];
    [self.backHeaderView addSubview:self.loginButton];
    [self.backHeaderView addSubview:self.usernameLabel];
    
    [self.myTableView insertSubview:_headerImageView atIndex:0];
    [self.myTableView bringSubviewToFront:_backHeaderView];

}


- (void)theLoginBtnWillChanged{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL user_login_status = [defaults boolForKey:@"user_login_status"];
    [self.loginButton removeFromSuperview];
    [self.usernameLabel removeFromSuperview];
    self.loginButton = nil;
    self.usernameLabel = nil;
    self.loginButton.frame = CGRectMake(0, 0, 70, 15);
    self.usernameLabel.frame = CGRectMake(0, -20, 70, 15);
    
    if (!user_login_status){//未登录
        [self.backHeaderView addSubview:self.loginButton];
    }else{
        UserModel *userDao = [[UserModel alloc]init];
        NSArray *arr = [userDao selectNumberOfData:0];
        User *userItem = arr.firstObject;
        _usernameLabel.text = userItem.username;
        _usernameLabel.textColor = [UIColor whiteColor];
        _usernameLabel.font = [UIFont systemFontOfSize:9.8f];
        _usernameLabel.hidden = NO;
        [self.backHeaderView addSubview:self.loginButton];
        [self.backHeaderView addSubview:self.usernameLabel];
    }
    
    
}


#pragma mark getter & setter

- (UITableView *)myTableView{
    if (_myTableView == nil) {
        _myTableView = [[UITableView alloc]initWithFrame:self.view.bounds];
        _myTableView.backgroundColor = [UIColor whiteColor];
        _myTableView.contentInset = UIEdgeInsetsMake(HEADER_IMAGE_HEIGHT, 0,100, 0);
        _myTableView.showsVerticalScrollIndicator = NO;
//        _myTableView. = UITableViewStyleGrouped;
        
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        
        UIView *view = [[UIView alloc] init];
        view.frame = CGRectZero;
        [view setBackgroundColor:[UIColor clearColor]];
        _myTableView.tableFooterView = view;
        
    }
    return _myTableView;
}


- (UIView *)backHeaderView{
    if (!_backHeaderView) {
        _backHeaderView = [[UIView alloc]init];
        _backHeaderView.backgroundColor = [UIColor clearColor];
    }
    return _backHeaderView;
}

- (UIImageView *)headerImageView{
    if (!_headerImageView) {
        _headerImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, -HEADER_IMAGE_HEIGHT, self.view.bounds.size.width, HEADER_IMAGE_HEIGHT)];
        [_headerImageView setImage:[UIImage imageNamed:@"headImage"]];
        [_headerImageView setContentMode:UIViewContentModeScaleAspectFill];
        
        _headerImageView.backgroundColor = [UIColor whiteColor];
    }
    return _headerImageView;
}

- (UIImageView *)userHeadImageView{
    if (!_userHeadImageView) {
        _userHeadImageView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 20, 60, 60)];
        _userHeadImageView.backgroundColor = [UIColor whiteColor];
        [_userHeadImageView setImage:[UIImage imageNamed:@"avatar"]];
        _userHeadImageView.contentMode = UIViewContentModeScaleToFill;
        [_userHeadImageView makeViewCircle];
//        //添加手势
        _userHeadImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didClickedUserHeaderImageView:)];
        [_userHeadImageView addGestureRecognizer:tap];
        

    }
    return _userHeadImageView;
}

- (UIButton *)loginButton{
    if (!_loginButton) {
        _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginButton.backgroundColor = [UIColor clearColor];
        
//        [_loginButton setFrame:CGRectMake(-5, -20, 70, 15)];
        _loginButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        UIFont *font1 = [UIFont fontWithName:@"HelveticaNeue-Medium" size:13.0f];
        UIFont *font2 = [UIFont fontWithName:@"HelveticaNeue-Light"  size:13.0f];
        
        UIColor *loginColor = [UIColor colorWithRed:232/255.f green:170/255.f blue:135/255.f alpha:1.f];
        UIColor *registColor = [UIColor colorWithRed:210/255.f green:191/255.f blue:46/255.f alpha:1.f];
        
        NSDictionary *loginAttribs = @{
                                  NSForegroundColorAttributeName: loginColor,
                                  NSFontAttributeName: font2
                                  };
        NSDictionary *registerAttribs =  @{
                                    NSForegroundColorAttributeName: registColor,
                                    NSFontAttributeName: font1
                                           
                                           };
        
        
        NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]init];
        [attr appendAttributedString:[[NSAttributedString alloc]initWithString:@"登录" attributes:loginAttribs]];
        [attr appendAttributedString:[[NSAttributedString alloc]initWithString:@"/注册" attributes:registerAttribs]];
        
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        BOOL user_login_status = [defaults boolForKey:@"user_login_status"];
        if (!user_login_status){
            [_loginButton setAttributedTitle:attr forState:UIControlStateNormal];
        }else{
            [_loginButton setTitle:@"注销" forState:UIControlStateNormal];
            
        }
        
        
        
        _loginButton.titleLabel.numberOfLines = 0;
        _loginButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
        
        [_loginButton addTarget:self action:@selector(didClickedLoginButton:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _loginButton;
}




- (UILabel *)usernameLabel{
    if (!_usernameLabel) {
        _usernameLabel = [[UILabel alloc]init];
        _usernameLabel.numberOfLines = 0;
        _usernameLabel.textAlignment = NSTextAlignmentCenter;
        _usernameLabel.font = [UIFont systemFontOfSize:12.0f];
        _usernameLabel.hidden = YES;
        
    }
    return _usernameLabel;
}


//- (StatusTableViewCell *)statusCell{
//    if (!_statusCell) {
//        _statusCell = [StatusTableViewCell cellWithTableView:_myTableView];
//        _statusCell.delegate = self;
//    }
//    return _statusCell;
//}
@end
